//
//  EasyTakePicViewModel.m
//  EnvironmentalProtection
//
//  Created by HCreater on 2018/9/27.
//  Copyright © 2018年 HCreater. All rights reserved.
//

#import "EasyTakePicViewModel.h"

#import "SSPPublishContentItemViewModel.h"

#import "SSPsListData.h"

@interface EasyTakePicViewModel()

@property (nonatomic, strong) ProvinceListData* zoneData;
@property (nonatomic, assign) NSInteger publishType;

@property (nonatomic, readwrite, strong) RACCommand* requestDataCmd;

@property (nonatomic, readwrite, strong) RACCommand* selectCmd;
@property (nonatomic, readwrite, strong) RACCommand* showDetailCmd;

@end

@implementation EasyTakePicViewModel

- (void)initialize
{
    [super initialize];
    
    @weakify(self);
    
    UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
    
    _publishTypeTitles = @[@"全部", @"生态宣传", @"污染曝光"];
    
    self.isMyself = NO;
    self.reqUserID = [um isLogined] ? um.userData.userID : @"";
    
    self.lastPage = 100;
    self.shouldMultiSections = YES;
    /// viewDidLoad后加载数据
    self.shouldRequestRemoteDataOnViewDidLoad = YES;
    /// 允许下拉刷新
    self.shouldPullDownToRefresh = YES;
    /// 允许上拉加载
    self.shouldPullUpToLoadMore = YES;
    
    /// 选中
    //    self.selectCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(ArticleItemViewModel * itemViewModel) {
    //        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
    //            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0), dispatch_get_main_queue(), ^{
    //                [subscriber sendNext:itemViewModel];
    //                [subscriber sendCompleted];
    //            });
    //            return nil;
    //        }];
    //    }];
    
    self.showDetailCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input)
    {
        @strongify(self);
        
        NSIndexPath* indexPath = input;
        
        SSPPublishContentItemViewModel* vm = self.dataSource[indexPath.section][0];
        SSPListData* listData = vm.data;
        
        return [[self requestCircleDetailSignal:listData.circleID] map:^id(id value)
        {
            SSPDetailData* detailData = value;
            detailData.isPraise = listData.isPraise;
            
            return @{@"List":listData, @"Detail":detailData};
        }];
    }];
    
    /// 允许并行执行
    self.selectCmd.allowsConcurrentExecution = NO;
    
    RACSignal* zoneChangeSignal = RACObserve(self, zoneData);
    RAC(self, zone) = [[zoneChangeSignal replay] map:^id(id value)
    {
        if (value == nil)
        {
            return @"全国";
        }
        
        ProvinceListData* curZoneData = value;
        
        return curZoneData.name;
    }];
    
    RACSignal* publishTypeChangeSignal = RACObserve(self, publishType);
    RAC(self, publishTitle) = [[publishTypeChangeSignal replay] map:^id(id value)
    {
        @strongify(self);
        
        NSInteger chooserIndex = [value integerValue];
        
        if (chooserIndex == 0)
        {
            return @"发布选择";
        }
        
        return self.publishTypeTitles[[value integerValue]];
    }];
    
    [[[zoneChangeSignal replay] merge:[publishTypeChangeSignal replay]] subscribeNext:^(id x)
     {
         @strongify(self);
         
         [self.requestRemoteDataCommand execute:@0];
     }];
}

- (void)resetZoneData:(ProvinceListData*)zoneData
{
    self.zoneData = zoneData;
}

- (void)resetPublishType:(NSInteger)publishType
{
    self.publishType = publishType;
}

- (RACSignal *)requestRemoteDataSignalWithPage:(NSUInteger)page
{
    @weakify(self)
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        
        @strongify(self);
        
        NSInteger reqPage = page+1;
        NSString* strUserID = (self.reqUserID!=nil && [self.reqUserID isNotBlank]) ? self.reqUserID : @"";
        NSString* strCategory = self.isMyself ? @"2" : @"1"; //1随手拍列表 2我的发布
        NSString* strType = HCStrFormat(@"%d", self.publishType); //1生态风景 2污染曝光
        NSString* strAreaID = (self.zoneData.areaID!=nil && [self.zoneData.areaID isNotBlank]) ? self.zoneData.areaID : @"";
        
        NSDictionary* postData = interface_param_circleList(@(reqPage), @(List_PageSize), strUserID, strCategory, strType, strAreaID);
        
        @weakify(self);
        return [[AFNetWorkUtils racPOSTWthURL:url_interface_circleList params:postData] subscribeNext:^(id x)
                {
                    @strongify(self)
                    
                    /// 转化数据
                    @weakify(self);
                    
                    SSPsListData* sspsListData = [SSPsListData modelWithJSON:x];
                    
                    NSArray *viewModels = [sspsListData.datas.rac_sequence map:^NSArray *(SSPListData* data)
                                           {
                                               @strongify(self);
                                               
                                               data.isMyself = self.isMyself;
                                               SSPPublishContentItemViewModel *itemViewModel = [[SSPPublishContentItemViewModel alloc] initWithData:data cellHeight:self.cellHeight];
                                               itemViewModel.isShowDetail = NO;
                                               
                                               return @[itemViewModel];
                                           }].array;
                    
                    if (viewModels == nil || viewModels.count < List_PageSize)
                    {
                        self.lastPage = self.page;
                        
                        if (viewModels == nil)
                            viewModels = @[];
                    }
                    else
                    {
                        self.lastPage = 999;
                    }
                    
                    if (self.shouldPullUpToLoadMore)
                    {
                        if (0 == page)
                        {
                            self.dataSource = viewModels;
                        }
                        else
                        {
                            if (self.dataSource == nil)
                            {
                                self.dataSource = viewModels;
                            }
                            else
                            {
                                self.dataSource = [self.dataSource arrayByAddingObjectsFromArray:viewModels];
                            }
                        }
                    }
                    else
                    {
                        self.dataSource = viewModels;
                    }
                    
                    
                    [subscriber sendNext:nil];
                    [subscriber sendCompleted];
                }   error:^(NSError *error) {
                    //错误处理
                    
                    [subscriber sendError:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:error.userInfo[customErrorInfoKey]}]];
                    [subscriber sendCompleted];
                }
                ];
        
        return nil;
    }];
}

- (RACSignal *)requestCircleDetailSignal:(NSString*)circleID
{
    @weakify(self)
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        
        @strongify(self)
        
        @weakify(self);
        NSDictionary* postData = interface_param_circleDetail(circleID);
        
        [[AFNetWorkUtils racPOSTWthURL:url_interface_circleDetail params:postData] subscribeNext:^(id x)
         {
             @strongify(self)
             
             SSPDetailData* sspDetailData = [SSPDetailData modelWithJSON:x];
             
             [subscriber sendNext:sspDetailData];
             [subscriber sendCompleted];
         }   error:^(NSError *error) {
             //错误处理
             
             [subscriber sendError:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:error.userInfo[customErrorInfoKey]}]];
             [subscriber sendCompleted];
         }];
        
        return nil;
    }];
}

@end
